<template>
	<view class="body" :class="{'no-scroll': isMask}">
		<view v-if="isMask" class="mask" @click="onMask"></view>
		<view class="bg">
			<image :src="$IMAGE_BASE_URL + '/img/new/bg.png'"
				style="width: 100%; height:671rpx;margin: auto; display: block;"></image>
		</view>
		<view class="home">
			<view @click="showhome = true"><text style="display: inline-block;float: left; white-space: nowrap; overflow: hidden;text-overflow: ellipsis; max-width: 200px;">{{chooseHome.label}}</text> <u-icon name="arrow-down-fill" color="#040303"
					size="28"></u-icon></view>
			<u-select v-model="showhome" :list="homelist" @confirm="confirm"></u-select>
			<view v-if="isManager || isOwer" class="add" @click="onShowAddView">
				<u-icon name="plus" color="#383838" size="32"></u-icon>
				<view v-if="isAddView" class="add-list">
					<view class="add-list-item" @click="onAddDevice">添加设备</view>
					<view class="add-list-item" @click="onAddMember">添加成员</view>
				</view>
			</view>
		</view>
		<view class="memberList">
			<view class="list" v-for="(val, index) in memberList" :key="index">
				<view @click="chooseMember(val)">
					<!-- <image v-if="val.choose == '1'" class="choosebg"
						:src="$IMAGE_BASE_URL + '/img/new/memberChoose.png'"></image> -->
						<view v-if="val.choose == '1'" class="ripple">
												<view style="--i:1"></view>
												<view style="--i:2"></view>
												<view style="--i:3"></view>
											</view>
					<image v-if="val.avatarUrl" :src='val.avatarUrl'
						style="width: 92rpx; height: 92rpx;margin:17rpx auto; display: block;border-radius: 50%;">
					</image>
					<image v-if="!val.avatarUrl" src='@/img/new/moren.png'
						style="width: 92rpx; height: 92rpx;margin:17rpx auto; display: block;"></image>
					<view class="name" v-if="val.remark == null">{{val.nickName==null?'游客':val.nickName}}</view>
					<view class="name" v-else>{{val.remark}}</view>
					<view class="age">（{{val.age != null?val.age:'--'}}岁）</view>
				</view>
			</view>
			<!-- <view class="list">
				<image src="../../img/new/mama.png"
					style="width: 92rpx; height: 92rpx;margin:17rpx auto; display: block;"></image>
				<view class="name">妈妈</view>
				<view class="age">（45岁）</view>
			</view>
			<view class="list">
				<image src="../../img/new/nainai.png"
					style="width: 92rpx; height: 92rpx;margin:17rpx auto; display: block;"></image>
				<view class="name">奶奶</view>
				<view class="age">（45岁）</view>
			</view> -->
			<view v-if="isManager" class="list" @click="onAddMember">
				<!-- <image class="choosebg" src="/img/new/memberChoose.png"></image> -->
				<image :src="$IMAGE_BASE_URL + '/img/new/memberAdd.png'"
					style="width: 92rpx; height: 92rpx;margin:17rpx auto; display: block;"></image>
				<view class="name">添加</view>
			</view>
		</view>
		<view class="remind" @click="toTableLamp">
			<view class="riqi">
				{{tixing.date?tixing.date:'--'}}
				<text v-if="tixing.lunarDate">农历{{tixing.lunarDate}}</text>
				<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="42"></u-icon>
			</view>
			<view class="tixing">
				<image :src="$IMAGE_BASE_URL + '/img/new/tixing.png'"
					style="width: 44rpx; height: 48rpx;margin:16rpx 10rpx;"></image>
				健康提醒
			</view>
			<view class="info" style="font-weight: bold;">
				{{tixing.sceneName?tixing.sceneName:'暂无提醒'}}
			</view>
			<view class="time">
				{{tixing.time?'提醒时间：'+tixing.time:'请前往星梦云康添加提醒'}}
			</view>
		</view>
		<view class="taideng">
			<view class="title" style="font-weight: bold;">
				星梦云康
				<image src="@/img/new/set1.png"
					style="width: 46rpx; height: 46rpx;margin:0rpx 10rpx;float: right; margin: 15rpx 15rpx 0 0 ;"
					@click="toTableLamp">
				</image>
			</view>
			<view class="info" @click="jump('pages/chart/HealthReport/index',deviceInfo.report)">
				<view style="display: flex;">
					<image :src="$IMAGE_BASE_URL + '/img/new/shuimian.png'"
						style="width: 48rpx; height: 48rpx;margin:0rpx 10rpx;">
					</image>
					睡眠
				</view>
				<u-row>
					<u-col span="5">
						<view :class="getClassName()">
							<view class="pingfen">
								<view>睡眠评分</view>
								<view style="font-size: 60rpx;font-weight:bold;">
									{{deviceInfo.report?deviceInfo.report.value.sleepQualityScore:'--'}}
								</view>
								<view v-if="deviceInfo.report" class="biaoqian">
									{{qualityText(deviceInfo.report.value.sleepQualityScore) }}</view>
							</view>
						</view>
					</u-col>
					<u-col span="7">
						<view class="date-info">
							<view>有效睡眠时长</view>
							<!-- <view style="font-size: 80rpx;">10<text style="font-size: 26rpx;">时</text>15<text
									style="font-size: 26rpx;">分</text></view> -->
							<view style="font-size: 80rpx;">
								{{deviceInfo.report?formatSecondsToTime(deviceInfo.report.value.effectiveSleepDuration):'--'}}
							</view>
							<view class="ml10">
								<view class="yuan lv"></view> <text style="color: #b2b2b2;">入睡</text>
								{{deviceInfo.report?deviceInfo.report.value.sleepTimeh+':'+deviceInfo.report.value.sleepTimem:'--'}}
							</view>
							<view class="ml10">
								<view class="yuan zi"></view> <text style="color: #b2b2b2;">深睡</text>
								{{deviceInfo.report?formatSecondsToTime(deviceInfo.report.value.deepSleepDuration):'--'}}<text
									style="color: #733ff1;">({{deviceInfo.report?(deviceInfo.report.value.deepSleep*1).toFixed(0):'--'}}%)</text>
							</view>
						</view>
					</u-col>
				</u-row>
				<view class="list"></view>
				<!-- </view> -->
				<!-- <view class="info" @click="jump('pages/chart/HealthReport/index')"> -->
				<view class="list">
					<view style="display: flex;">
						<image :src="$IMAGE_BASE_URL + '/img/new/huxi.png'"
							style="width: 48rpx; height: 48rpx;margin:0rpx 10rpx;">
						</image>
						呼吸
					</view>
					<view>

						<view class="data">
							{{deviceInfo.report?deviceInfo.report.value.avgRespiratoryRate:'--'}}<text>次/分钟</text>
						</view>
						<view class="fanwei">
							<view>{{deviceInfo.report?deviceInfo.report.value.minRespiratoryRate:'--'}}</view>
							<view>
								<image :src="$IMAGE_BASE_URL + '/img/new/xiegan.png'"
									style="width: 30rpx; height: 18.5rpx;"></image>
							</view>
							<view>{{deviceInfo.report?deviceInfo.report.value.maxRespiratoryRate:'--'}}</view>
							<view class="danwei">次/分钟</view>
						</view>
					</view>
				</view>
				<view class="list">
					<view style="display: flex;">
						<image :src="$IMAGE_BASE_URL + '/img/new/xinlv.png'"
							style="width: 48rpx; height: 48rpx;margin:0rpx 10rpx;">
						</image>
						心电
					</view>
					<view>
						<view class="data">
							{{deviceInfo.report?deviceInfo.report.value.avgHeartRate:'--'}}<text>bpm</text>
						</view>
						<view class="fanwei">
							<view>{{deviceInfo.report?deviceInfo.report.value.minHeartRate:'--'}}</view>
							<view>
								<image :src="$IMAGE_BASE_URL + '/img/new/xiegan.png'"
									style="width: 30rpx; height: 18.5rpx;"></image>
							</view>
							<view>{{deviceInfo.report?deviceInfo.report.value.maxHeartRate:'--'}}</view>
							<view class="danwei">bpm</view>
						</view>
					</view>
				</view>
				<view class="list">
					<view class="pilao">
						<!-- afResult fatigueResult -->
						<view class="name">疲劳程度</view>
						<view class="state lvcolor" style="line-height: 60rpx;">
							{{deviceInfo.fatigueResult_xmyk?deviceInfo.fatigueResult_xmyk.value:'--'}}
						</view>
					</view>
					<!-- <view class="pilao">
						<view class="name">精神张力</view>
						<view class="state">--</view>
					</view> -->
					<view class="pilao">
						<view class="name">房颤</view>
						<view class="state chengcolor" style="line-height: 60rpx;">
							{{deviceInfo.afResult_xmyk?deviceInfo.afResult_xmyk.value:'--'}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="taideng">
			<view class="title" style="font-weight: bold;">
				其他设备
				<image v-if="isManager || isOwer" :src="$IMAGE_BASE_URL + '/img/new/otherAdd.png'"
					style="width: 46rpx; height: 46rpx;margin:0rpx 10rpx;float: right; margin: 15rpx 15rpx 0 0 ;"
					@click="onAddDevice">
				</image>
			</view>
			<view v-for="(device, devicepIndex) in allDeviceTypes" :key="devicepIndex">
				<!-- @click="jump('pages/ECG/index',{iotDeviceId:device.iotDeviceId,deviceName:device.deviceName,productKey:device.productKey})" -->
				<view class="info w50 mr4" v-if="device.deviceType == 'ECG'" @click="jump('pages/chart/HRdata/index')">
					<view style="display: flex;">
						<image :src="$IMAGE_BASE_URL + '/img/new/xindian.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx;">
						</image>
						心率
					</view>
					<view class="data">
						{{deviceInfo.connection.value==1?deviceInfo.heartRate.value:'--'}}<text>bmp</text>
					</view>
					<view v-if="deviceInfo.connection.value==1">
						<view class="state2 red" v-if="deviceInfo.heartRate.value < alarm.BPM.downBpm"
							style="top:34rpx;">偏低</view>
						<view class="state2 red" v-else-if="deviceInfo.heartRate.value > alarm.BPM.upBpm"
							style="top:34rpx;">偏高</view>
						<view class="state2 lv" v-else style="top:34rpx;">正常</view>
					</view>
					<!-- <view class="device" v-if="device.nodevice">
						未绑定设备
					</view> -->
				</view>
				<!-- @click="jump('pages/SP02data/index',{iotDeviceId:device.iotDeviceId})" -->
				<view class="info w50 " v-if="device.deviceType == 'SPO'" @click="jump('pages/chart/SPO2data/index')">
					<view style="display: flex;">
						<image :src="$IMAGE_BASE_URL + '/img/new/xueyang.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx;">
						</image>
						血氧
					</view>
					<view class="data">
						<text
							v-if="deviceInfo.spo2">{{deviceInfo.spo2.value > 100 || deviceInfo.spo2.value  < 0?'--':deviceInfo.spo2.value}}</text>
						<text v-else>--</text>
						<text>%</text>
						<!-- {{device.info.spo2.value}}<text>%</text> -->
					</view>
					<view v-if="deviceInfo.spo2">
						<view class="state2 red" v-if="deviceInfo.spo2.value < alarm.SPO.down" style="top:34rpx;">偏低
						</view>
						<view class="state2 lv"
							v-if="deviceInfo.spo2.value > alarm.SPO.down && deviceInfo.spo2.value <100"
							style="top:34rpx;">正常</view>
					</view>
				</view>
				<!-- @click="jump('pages/BPdata/BPdata',{iotDeviceId:device.iotDeviceId})" -->
				<view class="info" style="clear: both;" v-if="device.deviceType == 'BP'"
					@click="jump('pages/chart/BPdata/index')">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/new/xueya.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image>
						血压
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="data2">
						{{deviceInfo.Sbp?deviceInfo.Sbp.value:'--'}}/{{deviceInfo.Dbp?deviceInfo.Dbp.value:"--"}}<text>mmHg</text>
					</view>
					<view v-if="deviceInfo.Sbp&&alarm.BP">
						<view class="state2 red"
							v-if="deviceInfo.Sbp.value > alarm.BP.upSbp*1 || deviceInfo.Dbp.value >alarm.BP.upDbp">偏高
						</view>
						<view class="state2 red"
							v-else-if="deviceInfo.Sbp.value < alarm.BP.downSbp || deviceInfo.Dbp.value <alarm.BP.downDbp">
							偏低</view>
						<view class="state2 lv" v-else>正常</view>
					</view>
				</view>
				<!-- @click="jump('pages/BGdata/index',{iotDeviceId:device.iotDeviceId})" -->
				<view class="info" style="clear: both;" v-if="device.deviceType == 'BG'"
					@click="jump('pages/chart/BGdata/index')">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/new/xuetang.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image>
						血糖
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="data2">
						<text
							style="color: #f78f00;padding-right: 40rpx; font-size: 30rpx;">{{deviceInfo.SugarState?deviceInfo.SugarState.value:'--'}}</text>
						{{deviceInfo.Result?deviceInfo.Result.value:'--'}}<text
							style="padding-right: 10rpx;">mmol/L</text>
						<!-- <u-icon name="arrow-upward" color="#ff2727" size="40"></u-icon> -->
					</view>
					<!-- <view class="state2 red">偏高</view> -->
					<view v-if="deviceInfo.Result">
						<view class="state2 red" v-if="deviceInfo.Result.bloodSugarLevel=='偏高'">偏高</view>
						<view class="state2 red" v-else-if="deviceInfo.Result.bloodSugarLevel=='偏低'">偏低</view>
						<view class="state2 lv" v-else>正常</view>
					</view>
				</view>
				<!-- @click="jump('pages/FallRecord/index',{iotDeviceId:device.iotDeviceId})" -->
				<view class="info" style="clear: both;" v-if="device.deviceType == 'UA'"
					@click="jump('pages/chart/UAdata/index')">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/new/niaosuan.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image>
						尿酸
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="data2">
						{{deviceInfo.UricAcid?deviceInfo.UricAcid.value:'--'}}<text style="padding-right: 20rpx;">μmol/L
						</text>
					</view>
					<view v-if="deviceInfo.UricAcid">
						<view class="state2 red" v-if="deviceInfo.UricAcid.value > alarm.UA.upUa">偏高
						</view>
						<view class="state2 red" v-else-if="deviceInfo.UricAcid.value < alarm.UA.downUa">偏低</view>
						<view class="state2 lv" v-else>正常</view>
					</view>
				</view>
				<view class="info" style="clear: both;" v-if="device.deviceType == 'BHB'"
					@click="jump('pages/chart/BHBdata/index')">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/new/xuetong.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image>
						血酮
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="data2">
						{{deviceInfo.BloodKetone?deviceInfo.BloodKetone.value:'--'}}<text
							style="padding-right: 20rpx;">mmol/L</text>
						<!-- <u-icon name="arrow-upward" color="#ff2727" size="40"></u-icon> -->
					</view>
					<view v-if="deviceInfo.BHB">
						<view class="state2 red" v-if="deviceInfo.BHB.value > alarm.BHB.upBhb">偏高
						</view>
						<view class="state2 lv" v-else>正常</view>
					</view>
				</view>
				<view class="info" style="clear: both;" v-if="device.deviceType == 'TC'"
					@click="jump('pages/chart/TCdata/index')">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/new/tc.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image>
            总胆固醇/血脂
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="data2">
						{{deviceInfo.Cholesterol?deviceInfo.Cholesterol.value:'--'}}<text
							style="padding-right: 20rpx;">mmol/L</text>
						<!-- <u-icon name="arrow-upward" color="#ff2727" size="40"></u-icon> -->
					</view>
					<view v-if="deviceInfo.Cholesterol">
						<view class="state2 red" v-if="deviceInfo.Cholesterol.value > alarm.TC.upTc">偏高
						</view>
						<view class="state2 lv" v-else>正常</view>
					</view>
				</view>
				<view class="info" style="clear: both;" v-if="device.deviceType == 'WEIGHT'"
					@click="jump('pages/chart/Weightdata/index')">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/weightxiao.png'"
							style="width: 52rpx; height: 52rpx;margin:0rpx 10rpx; float: left;"></image>
						体重
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="data2">
						{{deviceInfo.weight?deviceInfo.weight.value:'--'}}<text style="padding-right: 20rpx;">kg</text>
						<!-- <u-icon name="arrow-upward" color="#ff2727" size="40"></u-icon> -->
					</view>
					<!-- <view v-if="deviceInfo.Cholesterol">
						<view class="state2 red"
							v-if="deviceInfo.Cholesterol.value > alarm.TC.upTc">偏高
						</view>
						<view class="state2 lv" v-else>正常</view>
					</view> -->
				</view>
				<view class="info" style="clear: both;" v-if="device.deviceType == 'DIEDAO'">
					<view>
						<image :src="$IMAGE_BASE_URL + '/img/new/diedao.png'"
							style="width: 41rpx; height: 36rpx;margin:5rpx 10rpx; float: left;"></image>
						跌倒监测
						<u-icon style="float: right;" name="more-dot-fill" color="#515151" size="52"></u-icon>
					</view>
					<view class="diedao">
						<view v-if="deviceInfo.state">
							<text>上一次报警时间</text>{{$u.timeFormat(deviceInfo.state.time*1, 'yyyy-mm-dd hh:MM:ss')}}
							<image :src="$IMAGE_BASE_URL + '/img/new/sxt.png'"
								style="width: 104rpx; height: 47rpx;margin:16rpx 10rpx; float: right;"></image>
						</view>
						<view v-else>暂未发现跌倒</view>
					</view>
				</view>
			</view>
		</view>
		<!-- <u-popup v-model="showBPalarm" mode="center" border-radius="15" width="80%">
			<view style="padding: 30rpx;">
				<view>修改血压报警信息</view>
				<u-form :model="BPalarm" ref="BPalarm">
					<u-form-item label="通知号码" label-width='120' prop="notifyAddress"><u-input
							v-model="BPalarm.notifyAddress" :border="true" type='number'
							clearable='true' /></u-form-item>
					<view style="display: flex;">
						<u-form-item label="舒张压" label-width='120' prop="downSbp">
							<u-input v-model="BPalarm.downSbp" :border="true" type='number' input-align='center'
								clearable='true' />
						</u-form-item>
						<text style="padding: 0 10rpx;line-height: 106rpx;">-</text>
						<u-form-item prop="upSbp" label-width='0'>
							<u-input v-model="BPalarm.upSbp" :border="true" type='number' input-align='center'
								clearable='true' />
						</u-form-item>
					</view>
					<view style="display: flex;">
						<u-form-item label="收缩压" label-width='120' prop="downDbp">
							<u-input v-model="BPalarm.downDbp" :border="true" type='number' input-align='center'
								clearable='true' />
						</u-form-item>
						<text style="padding: 0 10rpx;line-height: 106rpx;">-</text>
						<u-form-item prop="upDbp" label-width='0'>
							<u-input v-model="BPalarm.upDbp" :border="true" type='number' input-align='center'
								clearable='true' />
						</u-form-item>
					</view>
					<u-button @click="submit">提交</u-button>
				</u-form>
			</view>
		</u-popup> -->
		<u-popup v-model="showTIshi" mode="center" border-radius="15" width="80%" z-index="888">
			<view class="popup" style="background: linear-gradient(180deg,#80f9e4, #fff); height: 210rpx;text-align: center;">
				<image src="@/img/new/tishi.png" style="width: 96rpx; height: 82rpx; display: block;padding: 45rpx 0 25rpx 0 ; margin: auto;"></image>
				请先绑定星梦云康！
			</view>
		</u-popup>
		<u-toast ref="uToast1"></u-toast>
	</view>
</template>
<script>
	import {
		setCartTabBadge
	} from '@/core/app'
	import LunarCalendar from 'lunar-calendar'
	import UserService from '@/service/UserService.js'
	import CacheConfig from "../../config/CacheConfig";
	import * as UserApi from '@/api/user';
	import * as AddressApi from '@/api/address'
	import {
		device,
		home,
		homeList,
		homeMembers,
		getalarm,
		postalarm
	} from "../../api/login/index.js";
	import {
		getPropert,
		propertLast,
		getScenenotify
	} from "../../api/device/index.js";
	import StorageUtils from "../../utils/StorageUtils";
	import SimDevice from '../../service/mqtt/sim/SimDevice.js';
	import {
		DeviceBasicData
	} from '../../service/mqtt/DeviceConfig.js';
	import {
		checkBloodSugarStatus
	} from '@/common/alarm/BG.js'

	export default {
		data() {
			return {
				showTIshi:false,
				allDeviceTypes: [{
					deviceType: 'LIGHT', //SHUIMIAN
					nodevice: true
				}, {
					deviceType: 'ECG',
					nodevice: true
				}, {
					deviceType: 'SPO',
					nodevice: true
				}, {
					deviceType: 'BP',
					nodevice: true
				}, {
					deviceType: 'BG',
					nodevice: true
				}, {
					deviceType: 'UA',
					nodevice: true
				}, {
					deviceType: 'TC',
					nodevice: true
				}, {
					deviceType: 'BHB',
					nodevice: true
				}, {
					deviceType: 'WEIGHT',
					nodevice: true
				}, {
					deviceType: 'DIEDAO',
					nodevice: true
				}], //设备类型
				identifiers: ['rr', 'state', 'heartRate', 'spo2', 'Sbp', 'Dbp', 'Result', 'UricAcid', 'Cholesterol',
					'BloodKetone', 'weight', 'mrr', 'mhr', 'afResult_xmyk', 'fatigueResult_xmyk', 'SugarState'
				], //设备标识符
				showBPalarm: false,
				BPalarm: {}, //bp警报
				chartData: {},
				showhome: false,
				alarm: {
					"BP": {
						"upSbp": 140,
						"notifyType": "MESSAGE",
						"upDbp": 90,
						"downSbp": 90,
						"downDbp": 60
					},
					"BG": {
						"breakfastTime": "07:30",
						"lunchTime": "11:30",
						"upAfter1": 9.4,
						"notifyType": "MESSAGE",
						"downEmpty": 3.9,
						"downAfter1": 6.7,
						"upAfter2": 7.8,
						"upEmpty": 6.1,
						"dinnerTime": "17:30",
						"downAfter2": 3.9
					},
					"BPM": {
						"upBpm": 100,
						"notifyType": "MESSAGE",
						"downBpm": 60
					},
					"SPO": {
						"notifyType": "MESSAGE",
						"down": 90
					},
					"UA": {
						"notifyType": "MESSAGE"
					}
				},
				homelist: [{
					value: '1',
					label: '我的家庭'
				}],
				chooseHome: {
					value: '1',
					label: '我的家庭'
				},
				deviceInfo: {
					connection: {
						value: 0
					},
				},
				//设备列表
				deviceList: {},
				memberList: [{
					name: '我'
				}],
				tabcurrent: 0,
				// 添加弹窗
				isAddView: false,
				// 遮罩
				isMask: false,
				//提醒
				tixing: {},
				//taideng
				LIGHT: {}
			};
		},
		computed: {
			isManager() {
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				return this.chooseHome.userId == userInfo.id;
			},
			isOwer() {
				const member = this.memberList.find(v => v.choose == 1);
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				return !!member && member.id == userInfo.id;
			},
		},
		onReady() {
			// this.getServerData();
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// 当前页面参数
			this.options = options;
			this.login()

		},
		onUnload() {},
		onShow() {
			// 更新购物车角标
			// #ifdef MP-WEIXIN
			// setCartTabBadge();
			// #endif
			if (!!StorageUtils.get('ALARM') && !!StorageUtils.get('uuid')) {
				console.log('开始获取设备信息！');
				// this.getDevice(StorageUtils.get('uuid'))
				this.upInfo(StorageUtils.get('uuid'));
				let home = StorageUtils.get('home');
				this.chooseHome = home;
				this.getHomeMember(home.value,home.userId);
				// this.getAddressList()
				}
		},
		onHide() {
			if (this.mqttPing) {
				clearInterval(this.mqttPing);
				this.simDevice.close();
			}
			this.isMask = false;
			this.isAddView = false;
		},
		methods: {
			confirm(e) {
				// this.chooseHome = e[0];
				this.homelist.map(val=>{
					if(val.value == e[0].value){
						this.chooseHome = val;
						this.getHomeMember(e[0].value,val.userId);
						StorageUtils.save('home', val);
						StorageUtils.save('homeId', e[0].value);
					}
				})
			},
			// 获取收货地址列表
			getAddressList() {
			  const app = this
			  return new Promise((resolve, reject) => {
			    AddressApi.list()
			      .then(result => {
					  if(result.obj){
						  result.obj.map(val=>{
							  if(val.isDefault){
								  StorageUtils.remove('ChooseAddress')
								  StorageUtils.save('DefaultAddress', val);
							  }
						  })
					  }
			      })
			      .catch(reject)
			  })
			},
			//通过分数渐变
			getClassName() {
				let val = this.deviceInfo.report ? this.deviceInfo.report.value.sleepQualityScore : 100
				if (val >= 0 && val <= 59) {
					return 'bad jianbian';
				} else if (val >= 60 && val <= 89) {
					return 'general jianbian';
				} else if (val > 90) {
					return 'good jianbian';
				} else {
					return 'jianbian'; // 如果需要处理其他情况，可以返回默认类或空字符串
				}
			},
			//分数返回结果
			qualityText(val) {
				if (val >= 60 && val <= 89) {
					return '良好';
				} else if (val < 60) {
					return '差'; // 或者其他适当的文本
				} else {
					return '很好'; // 或者其他适当的文本
				}
			},
			//计算深睡时间
			formatSecondsToTime(seconds) {
				if (seconds == 0) {
					return '无'
				}
				// 计算小时数
				var hours = Math.floor(seconds / 3600);
				// 计算剩余的分钟数
				var minutes = Math.floor((seconds % 3600) / 60);
				// 如果小时数为0，则小时部分不显示（可选）
				var timeString = (hours > 0 ? hours + ':' : '0:') + minutes.toString().padStart(2, '0');
				return timeString + '';
			},
			onMask() {
				this.isMask = false;
				this.isAddView = false;
			},
			onShowAddView() {
				if(this.isManager) {
					this.isMask = true;
					this.isAddView = true;
				} else {
					this.onAddDevice();
				}
			},
			onAddDevice() {
				if (!this.$isLogin()) return;
				this.$addDeviceService.scanCode();
			},
			onAddMember() {
				console.log("添加成员");
				if (!this.$isLogin()) return;
				this.jump('pages/mine/invite');
			},
			toTableLamp() {
				const data = {
					iotDeviceId: this.LIGHT.iotDeviceId,
					deviceName: this.LIGHT.deviceName,
					productKey: this.LIGHT.productKey
				}
				this.jump('pages/tableLamp/tableLamp', data);
			},
			jump(url, data) {
				// console.log("jump", data);
				if (url == 'pages/tableLamp/tableLamp') {
					if (data.iotDeviceId == undefined) {
						// console.log(this.$refs.uToast1);
						// this.$refs.uToast1.show({
						// 	title: '请先绑定台灯！',
						// 	type: 'success'
						// })
						this.showTIshi=true;
						return false;
					}
					
				}
				if(url == 'pages/chart/HealthReport/index'){
					if(data){
						StorageUtils.save('ReportData', data.time);
					}else{
						StorageUtils.remove('ReportData');
					}
				}
				if (this.mqttPing) {
					clearInterval(this.mqttPing);
					this.simDevice.close();
				}
				this.$navTo(url, {
					...data
				}, )
			},
			// showAlarm(obj) {
			// 	getalarm({
			// 		alarmType: obj
			// 	}).then(res => {
			// 		if (obj == 'BP') {
			// 			this.BPalarm = JSON.parse(res.obj.alarmContent)
			// 		}
			// 		this.showBPalarm = true
			// 	})
			// },
			submit() {
				this.$refs.BPalarm.validate(valid => {
					if (valid) {
						postalarm({
							alarmType: 'BP',
							alarmContent: JSON.stringify(this.BPalarm)
						}).then(res => {
							this.showBPalarm = false
							this.$refs.uToast1.show({
								title: '修改成功！',
								type: 'success'
							})
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			mqtt(device) {
				let deviceBasicData = new DeviceBasicData('', '', undefined);
				this.simDevice = new SimDevice();
				let url = '47.97.72.174:1887';
				// let url = '123.60.177.231:1887';
				deviceBasicData.username = '1559108322@qq.com';
				deviceBasicData.password = '123456';
				deviceBasicData.addr = url;
				let that = this;
				this.simDevice.clientDataListener = {
					onHandle: (topic, msg) => {
						msg = msg.replace(/'/g, '"');
						if (JSON.parse(msg).method === 'thing.service.property.post') {
							let info = JSON.parse(msg);
							let item = info.params;
							let data={}
							if(item == undefined){
								return false;
							}
							if ('Result' in item) {
								let val = checkBloodSugarStatus(item.Result, JSON.parse(StorageUtils.get('ALARM')).BG);
								item.Result.bloodSugarLevel = val.bloodSugarLevel
							}
							if ('report' in item) {
								data.value = JSON.parse(item.value.replace(/-/g, ""))
								data.report = item;
							}
							this.deviceInfo = {
								...this.deviceInfo,
								...item,
								...data
							}
							// console.log(that.deviceInfo);
						}
					},
					onSetProperty: (requestPayload) => {
						let params = requestPayload.params;
					},
					onConnect(success) {
						// console.log('连接服务器:' + success);
						if (success) {
							device.map(val => {
								if (val.deviceType == "LIGHT") {
									that.LIGHT = val
								}
								that.simDevice.subscribe(val.productKey, val.deviceName)
							})
							that.mqttPing = setInterval(() => {
								that.simDevice.ping()
							}, 30000);
						}
					},
					onClose() {
						console.log('连接关闭');
					}
				};
				this.simDevice.init(deviceBasicData);
				this.simDevice.connectServer();
			},
			async login() {
				await UserService.wxLogin();
				let home = StorageUtils.get('home');
				if (!!home) {
					let home=StorageUtils.get('home')
					this.getHomeMember(home.value,home.userId)
					this.chooseHome = home;
					StorageUtils.save("homeId", home.value);
				}
				homeList().then(res => {
					let homelist = []
					res.obj.map((val, index) => {
						if (index == 0 && !home) {
							this.getHomeMember(val.id, val.userId)
							this.chooseHome = {
								value: val.id,
								label: val.homeName,
								userId: val.userId
							}
							StorageUtils.save("homeId", val.id);
						}
						homelist.push({
							value: val.id,
							label: val.homeName,
							userId: val.userId
						})
					})
					this.homelist = homelist
				})
				if (!StorageUtils.get('uuid')) {
					let uuid = UserService.userInfo.uuid;
					// console.log("uuid", uuid);
					// uuid = 100143
					StorageUtils.save('uuid', uuid);
					// setCartTabBadge();
					this.upInfo(uuid);
				} else {
					this.upInfo(StorageUtils.get('uuid'));
				}
			},
			upInfo(uuid) {
				const now = new Date();
				let newdata = this.$u.timeFormat(now, 'mm-dd')
				const lunar = LunarCalendar.solarToLunar(now.getFullYear(), now.getMonth() + 1, now.getDate());
				const lunarDate = `${lunar.lunarMonth}月${lunar.lunarDay}日`;
				this.tixing = {
					date: newdata,
					lunarDate,
				}
				let that = this;
				// if(!StorageUtils.get('ALARM')||uuid !=StorageUtils.get('uuid')){

				// }
				// if (!!StorageUtils.get('ALARM')) {
				// 	this.alarm = StorageUtils.get('ALARM');
				// }
				getalarm({
					userId: uuid
				}).then(res => {
					const transformedData = {};
					let alarm = {}
					res.obj.forEach(item => {
						let alarmType = item.alarmType;
						let alarmContent = JSON.parse(item.alarmContent);
						alarm[alarmType] = alarmContent;
					});
					that.alarm = alarm
					StorageUtils.save('ALARM', JSON.stringify(this.alarm));
					StorageUtils.save('uuid', uuid);
					this.getDevice(uuid)
					getScenenotify({
						uuid: uuid
					}).then(res => {
						if (res.obj.length > 0) {
							this.tixing = this.findNearestReminder(res.obj)
						}
					})
				}).catch(error => {});
				
			},
			findNearestReminder(scenes) {
				const now = new Date();
				const currentDay = now.getDay();
				const currentHour = now.getHours();
				const currentMinute = now.getMinutes();

				let nearestScene = null;
				let nearestTimeDiff = Infinity;
				let nearestReminderTime = null;

				const dayMap = {
					"SUNDAY": 0,
					"MONDAY": 1,
					"TUESDAY": 2,
					"WEDNESDAY": 3,
					"THURSDAY": 4,
					"FRIDAY": 5,
					"SATURDAY": 6
				};

				scenes.forEach(scene => {
					if (scene.inUse) {
						const conditions = JSON.parse(scene.conditionJson);
						conditions.forEach(condition => {
							const {
								logicFrequency,
								hour,
								minute
							} = condition;
							logicFrequency.forEach(dayStr => {
								const day = dayMap[dayStr];
								let daysDiff = day - currentDay;
								if (daysDiff < 0) {
									daysDiff += 7;
								}
								let reminderTime = new Date(now.getFullYear(), now.getMonth(),
									now.getDate() + daysDiff, hour, minute);
								let timeDiff = reminderTime.getTime() - now.getTime();
								if (timeDiff < 0) {
									reminderTime = new Date(now.getFullYear(), now.getMonth(),
										now.getDate() + 7, hour, minute)
									timeDiff = reminderTime.getTime() - now.getTime();
								}
								if (timeDiff > 0 && timeDiff < nearestTimeDiff) {
									nearestTimeDiff = timeDiff;
									nearestScene = scene;
									nearestReminderTime = reminderTime;
								}
							});
						});
					}
				});
				if (nearestScene) {
					const lunar = LunarCalendar.solarToLunar(nearestReminderTime.getFullYear(), nearestReminderTime
						.getMonth() + 1, nearestReminderTime.getDate());
					const lunarDate = `${lunar.lunarMonth}月${lunar.lunarDay}日`;
					const formattedDate =
						`${String(nearestReminderTime.getMonth() + 1).padStart(2, '0')}-${String(nearestReminderTime.getDate()).padStart(2, '0')}`;
					const formattedTime =
						`${String(nearestReminderTime.getHours()).padStart(2, '0')}:${String(nearestReminderTime.getMinutes()).padStart(2, '0')}`;

					return {
						sceneName: nearestScene.sceneName,
						date: formattedDate,
						time: formattedTime,
						lunarDate: lunarDate
					};
				}

				return null;
			},
			getHomeMember(id, userId) {
				homeMembers({
					homeId: id
				}).then(res => {
					let uuid = StorageUtils.get('uuid');
					// let homeId=StorageUtils.get('homeId');
					res.obj.map((val, index) => {
						if (uuid == val.uuid) {
							res.obj[index].choose = 1;
							// this.currentUuid = res.obj[index].uuid;
						}
					})
					
					this.memberList = this.moveMatchedUuidToFirst(res.obj, userId);;
				})
			},
			moveMatchedUuidToFirst(arr, userId) {
				// 复制数组避免修改原数据
				const newArray = [...arr];
				// 查找匹配项的索引
				const index = newArray.findIndex(item => item.id === userId);

				if (index !== -1) {
					// 从原位置删除
					const matchedItem = newArray.splice(index, 1)[0];
					// 插入到数组开头
					newArray.unshift(matchedItem);
				}
				return newArray;
			},
			chooseMember(val) {
				this.deviceInfo = {
					connection: {
						value: 0
					},
				}
				this.LIGHT = {}
				this.memberList.map((val1, vindex) => {
					if (val1.uuid == val.uuid) {
						val1.choose = 1;
						this.upInfo(val.uuid);
						//当前选择的人
					} else {
						val1.choose = 0;
					}
				})
			},
			lastData() {
				propertLast().then(res => {
					const result = {};
					let obj = res.obj
					console.log(res);
					if (obj == null) return false;
					Object.keys(obj).forEach(key => {
						if (key == 'Result') {
							let val = checkBloodSugarStatus(obj[key], JSON.parse(StorageUtils.get('ALARM'))
								.BG);
							obj.Result.bloodSugarLevel = val.bloodSugarLevel
						}
						if (key == 'report') {
							obj.report.value = JSON.parse(obj.report.value.replace(/-/g, ""))
						}
						if (key == 'weight') {
							this.memberList.map((val, vindex) => {
								if (StorageUtils.get('uuid') == val.uuid && obj.weight.value * 1 !=
									val.weight) {
									const param = {
										weight: obj.weight.value * 1,
										id: val.id,
										appid: "wx9defdd2125f88fbb"
									};
									UserApi.updateUserInfoById(param).then(res => {
										console.log(1);
									}).catch(err => {
										// console.log("updateUserInfo error", err);
									});
								}
							})
						}
						result[key] = obj[key];
					});
					this.deviceInfo = {
						...this.deviceInfo,
						...result
					}
				});
			},
			getDevice(uuid) {
				device({
					uuid: uuid
				}).then(async res => {
					this.lastData()
					try {
						let types = this.allDeviceTypes;
						let devices = res.obj;
						for (let i = 0; i < types.length; i++) {
							// 遍历第二个数组查找匹配项
							for (let j = 0; j < devices.length; j++) {
								// 检查deviceType是否包含typesArray中的type
								// 注意：这里使用includes和toLowerCase进行简单的字符串匹配
								// 如果deviceType包含type（不区分大小写），则更新nodevice属性
								if (devices[j].deviceType.toLowerCase().includes(types[i].deviceType
										.toLowerCase())) {
									types[i].nodevice = false; // 设置为false表示已连接设备
									types[i].iotDeviceId = devices[j].iotDeviceId;
									// productKey deviceName
									types[i].productKey = devices[j].productKey;
									types[i].deviceName = devices[j].deviceName;
									break; // 找到匹配项后退出内层循环
								}
							}
						}
						// this.allDeviceTypes = types.sort((a, b) => a.nodevice ? 1 : -1);
						this.allDeviceTypes = types
						this.deviceList = res.obj;
						if (this.mqttPing) {
							clearInterval(this.mqttPing);
							this.simDevice.close();
						}
						console.log('设备信息！' + JSON.stringify(res.obj));
						this.mqtt(res.obj)
					} catch (error) {
						console.error('Error fetching device info:', error);
					}
				}).catch(error => {
					console.error('Error fetching devices:', error);
				});
			},

		}
	};
</script>>



<style lang="scss">
	.bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
	}

	.body {
		padding: 180rpx 28rpx 0;
		color: #040303;
		background-color: #eef0f2;
	}

	.no-scroll {
		position: fixed;
		width: 100%;
		height: 100vh;
		/* 设置为视口高度 */
		overflow: hidden;
	}

	.mask {
		width: 100vw;
		height: 100vh;
		background: rgba(0, 0, 0, 0);
		position: absolute;
		left: 0;
		top: 0;
		z-index: 99;
	}

	.home {
		font-size: 36rpx;
		display: flex;
		line-height: 50rpx;
		position: relative;
		z-index: 99;

		.add {
			border-radius: 25rpx;
			background-color: #f5f5f5;
			text-align: center;
			width: 50rpx;
			margin-left: auto;
			position: relative;

			.add-list {
				width: 200rpx;
				position: absolute;
				right: 0;
				bottom: -150rpx;
				border-radius: 20rpx;
				background-color: #FFFFFF;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);

				.add-list-item {
					font-size: 30rpx;
					padding: 10rpx 0;
				}
			}
		}


	}

	.memberList {
		display: flex;
		margin: 30rpx 0 0 0;
		flex-wrap: wrap;
		position: relative;
		z-index: 1;

		.name {
			font-size: 30rpx;
			margin-top: 20rpx;
		}

		.age {
			font-size: 24rpx;
		}

		.list {
			width: 25%;
			text-align: center;
			position: relative;

			.choosebg {
				position: absolute;
				z-index: -1;
				width: 130rpx;
				height: 130rpx;
				top: -1rpx;
				margin: auto;
				display: block;
				left: calc(50% - 65rpx);
			}
		}
	}

	.remind {
		background-color: #a4eccf;
		border-radius: 30rpx;
		padding: 30rpx;
		margin-top: 20rpx;

		position: relative;
		z-index: 1;

		.riqi {
			font-size: 42rpx;
		}

		.tixing {
			display: flex;
			margin: 20rpx 0;
			font-size: 36rpx;
			line-height: 80rpx;
		}

		.info {
			font-size: 38rpx;
			line-height: 76rpx;
			border-radius: 10rpx;
			background-color: #ffe539;
			text-align: center;
			color: #2b2a2e;
		}

		.time {
			font-size: 24rpx;
			line-height: 76rpx;
			text-align: center;
		}
	}

	.taideng {
		margin-top: 20rpx;
		font-size: 36rpx;
		overflow: hidden;

		.title {
			font-size: 36rpx;
			line-height: 76rpx;
		}

		.w50 {
			float: left;
			width: 48%;

			.data {
				width: 100%;
				text-align: center;
			}
		}

		.mr4 {
			margin-right: 4%;
		}

		.info {
			margin-bottom: 10px;
			background-color: #fff;
			padding: 30rpx;
			border-radius: 30rpx;
			overflow: hidden;
			position: relative;
			font-size: 36rpx;

			.diedao {
				background-color: #f2f2f2;
				font-size: 28rpx;
				font-weight: bold;
				color: #fe2d2d;
				text-align: center;
				line-height: 80rpx;
				margin-top: 20rpx;
			}

			.state2 {
				width: 72rpx;
				height: 36rpx;
				line-height: 36rpx;
				border-radius: 6rpx;
				position: absolute;
				top: 130rpx;
				right: 35rpx;
				font-size: 24rpx;
				color: #fff;
				text-align: center;
			}

			.data {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 150rpx;
				float: left;

				text:last-child {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.data2 {
				font-size: 82rpx;
				font-weight: bold;
				line-height: 110rpx;
				text-align: center;

				text {
					padding-left: 10rpx;
					font-size: 26rpx;
				}
			}

			.fanwei {
				width: 100rpx;
				text-align: center;
				float: right;
				line-height: 36rpx;
				font-size: 26rpx;

				.danwei {
					font-size: 15.4rpx;
					color: #a0a0a0;
				}
			}

			.list {
				overflow: hidden;
				border-bottom: #f7f7f8 10rpx solid;
				padding-top: 30rpx;
			}

			.list:first-child {
				padding-top: 0;
			}

			.list:last-child {
				border: none;
			}

			.pilao {
				float: left;
				width: 50%;
				text-align: center;

				.name {
					font-size: 26rpx;
					font-weight: bold;
				}

				.state {
					font-size: 45rpx;
					line-height: 100rpx;
					font-weight: bold;
					color: #bbbbbb;
				}
			}
		}
	}

	.general {
		background: linear-gradient(to top right, #ccfff6, #07eacd) !important;

		.biaoqian {
			background-color: #07eacd !important;
		}
	}

	.bad {
		background: linear-gradient(to top right, #fbf7e4, #fdd209) !important;

		.biaoqian {
			background-color: #fdd209 !important;
		}
	}

	.jianbian {
		border-radius: 50%;
		overflow: hidden;
		background: linear-gradient(to top right, #b3fde3, #66de96);
		height: 100%;
		width: 100%;
		text-align: center;
		font-size: 24rpx;
		margin: 40rpx 0rpx 0 0;

		.biaoqian {
			width: 90rpx;
			margin: auto;
			background-color: #0cd10f;
			color: #fff;
			border-radius: 6rpx;
			line-height: 40rpx;
		}

		.pingfen {
			height: 190rpx;
			width: 190rpx;
			margin: 25rpx auto;
			background-color: #fff;
			border-radius: 50%;
			padding: 20rpx;
		}
	}

	.yuan {
		height: 30rpx;
		width: 30rpx;
		border-radius: 50%;
	}

	.lv {
		background-color: #0cd10f;
		margin-right: 10rpx;
	}

	.red {
		background-color: #ff2727;
	}

	.lvcolor {
		color: #0cd10f !important;
	}

	.chengcolor {
		color: #ffa126 !important;
	}

	.zi {
		background-color: #9270ff;
		margin-right: 10rpx;
	}

	.ml10 {
		font-size: 26rpx;
		margin-top: 20rpx;
		display: flex;

		text {
			margin-right: 10rpx;
		}
	}
	.ripple {
		position: absolute;
		top: -5rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: -1;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 130rpx;
		height: 130rpx;
		view {
			position: absolute;
			background: #81d3b7;
			box-sizing: border-box;
			border-radius: 100%;
			animation: animate 1s linear infinite;
			animation-delay: calc(0.5s * var(--i));
		}
	}
	@keyframes animate {
		0% {
			opacity: 0;
		}

		10% {
			width: 100rpx;
			height: 100rpx;
			opacity: 0.5;
		}

		50% {
			opacity: 0.5;
		}

		100% {
			width: 160rpx;
			height: 160rpx;
			opacity: 0;
		}
	}
</style>